//################################
// 版权所有：鸽子游戏俱乐部
// 系统名称：鸽子游戏俱乐部-移动版
// 文件名称：login.js
// 创建时间：2017年04月08日
// 创建人员：Lemo
// 功能说明：用户名密码登录页面
//################################

'use strict';

import React, {Component} from 'react';
import {
    Text,
    View,
    StyleSheet,
    Image,
    Dimensions,
    TextInput,
    TouchableOpacity,
    Alert,
    InteractionManager,
    NativeModules,
} from 'react-native';

import {
    CommonFunc,
    CommonData,
    UIConstants,
    Routes,
    PubSubTopics,
    Colors,
} from '../../common';
import Images from '../../images';

import CheckBox from '../../components/checkbox';
import Button from '../../components/button';

import {loginWithUsernamePassword, clearLoginFailedMsg, clearActionType} from '../../actions';
import LocalStorage from '../../utils/storageUtil';

import * as ActionTypes from '../../actions/types';

import MainContainer from '../../main/containers/mainContainer';

import NavigatorLevel1 from '../../main/pages/navigatorLevel1';

import SplashScreen from 'react-native-smart-splash-screen';
import Icon from 'react-native-vector-icons/Ionicons';
import PubSub from 'pubsub-js';

import {toastTip} from '../../utils/toastTipUtil';

import ConfirmDialog from '../../components/dialog';

import MyResetPwdContainer from '../../my/containers/myResetPwdContainer';

const WINDOW_WIDTH = Dimensions.get('window').width;
const WINDOW_HEIGHT = Dimensions.get('window').height;

class Login extends Component {
    constructor(props) {
        super(props);

        this.onLogin = this.onLoginFunc.bind(this);
        this.onSavePwdCheckChange = this.onSavePwdCheckChangeFunc.bind(this);
        this.onUsernameInputFocus = this.onUsernameInputFocusFunc.bind(this);
        this.onUsernameInputBlur = this.onUsernameInputBlurFunc.bind(this);
        this.clearUsernameInput = this.clearUsernameInputFunc.bind(this);
        this.onPasswordInputFocus = this.onPasswordInputFocusFunc.bind(this);
        this.onPasswordInputBlur = this.onPasswordInputBlurFunc.bind(this);
        this.clearPasswordInput = this.clearPasswordInputFunc.bind(this);

        this.isSavePwdChecked = false;
        this.isUsernameInputFocused = false;
        this.isPasswordInputFocused = false;
        
        this.state = {
            username: '',
            password: '',
            appVersion: '',

            title: '',
            content: '',
            confirmLabel: '',
            cancelLabel: '',
            confirmFunc: () => null,
            cancelFunc: () => null,
            dialogType: '',
            iconType: '',
        };
    }
    
    componentWillMount() {
        LocalStorage.getUserList((userList) => {this.gotUserList(userList)});
    }

    componentDidMount() {
        this.setState({
            appVersion: CommonData.appVersion,
        });
        SplashScreen.close("fade", 850, 500);
    }

    gotUserList(userList) {
        if (userList === null) {
            userList = [];
        }

        // 找到最近一次登录的用户信息
        for (let i = 0;i < userList.length;i++) {
            let user = userList[i];

            if (user.lastLogined) {
                this.isSavePwdChecked = user.isSavePwdChecked;

                if (this.props.route.isLogout) {
                    this.isSavePwdChecked = false;

                    userList[i].password = '';
                    userList[i].isSavePwdChecked = false;

                    LocalStorage.saveUserList(userList);
                }

                this.setState({
                    username: user.username,
                    password: this.isSavePwdChecked ? user.password : '',
                });

                if (this.props.route.data && this.props.route.data.isJumpFromGesturePasswordPage) {
                    this.isSavePwdChecked = false;
                    this.setState({
                        password: '',
                    });
                }

                break;
            }
        }
    }

    saveUserInfo() {
        let user = {
            username: this.state.username,
            password: this.state.password,
            isSavePwdChecked: this.isSavePwdChecked,
            gesturePwd: '',
            lastLogined: true,
        };

        LocalStorage.getUserList((userList) => {this.gotUserListAndSaveUserList(userList, user)});
    }

    gotUserListAndSaveUserList(userList, user) {
        if (CommonFunc.isEmpty(userList)) {
            userList = [];
            userList.push(user);

            LocalStorage.saveUserList(userList);
        }
        else {
            for (let i = 0;i < userList.length;i++) {
                userList[i].lastLogined = false;
            }

            // 查找账户是否已在列表中存在，如果不存在则更新userList并保存到storage
            let index = -1;

            for (let i = 0;i < userList.length;i++) {
                let userInfo = userList[i];

                if (user.username === userInfo.username && user.password === userInfo.password) {
                    index = i;
                    break;
                }
            }

            if (index === -1) {
                // 没找到，则在userList中新增一条记录
                userList.push(user);

                LocalStorage.saveUserList(userList);
            }
            else {
                // 找到了，判断是否需要更新isSavePwdChecked字段
                if (userList[index].isSavePwdChecked === user.isSavePwdChecked && userList[index].lastLogined === user.lastLogined) {
                    // 不处理
                }
                else {
                    userList[index].isSavePwdChecked = user.isSavePwdChecked;
                    userList[index].lastLogined = user.lastLogined;

                    LocalStorage.saveUserList(userList);
                }
            }
        }
    }
    
    componentWillReceiveProps(nextProps) {
        switch (nextProps.actionType) {
            case ActionTypes.LOGIN_LOGINWITHUSERNAMEPASSWORD_LOGIN_SUCCESS:
                this.loginSuccess(nextProps);
                break;
            case ActionTypes.LOGIN_LOGINWITHUSERNAMEPASSWORD_LOGIN_FALIED:
                this.loginFailed(nextProps);
                break;
            default:
                break;
        }
    }

    loginSuccess(nextProps) {
        // 将用户名密码存储到本地存储
        this.saveUserInfo();

        let userInfo = nextProps.data;
        CommonData.vipId = userInfo.vipId,
        CommonData.wangwang = userInfo.wangwang,
        CommonData.levelName = userInfo.levelName,
        CommonData.rentCount = userInfo.rentCount,
        CommonData.gameType = userInfo.gameType,
        CommonData.commission = userInfo.commission,
        CommonData.balance = userInfo.balance,
        CommonData.security = userInfo.security,
        CommonData.giftBalance = userInfo.giftBalance,
        CommonData.receiverName = userInfo.receiverName,
        CommonData.provinceId = userInfo.provinceId,
        CommonData.address = userInfo.address,

        PubSub.publish(PubSubTopics.SPINKIT_MODAL_CLOSE);

        setTimeout(() => {
            // 跳转到主页面
            nextProps.navigatorRoot.resetTo({
                name: Routes.MAIN_NAVIGATOR,
                component: NavigatorLevel1,
            });
        }, 500);
    }

    loginFailed(nextProps) {
        PubSub.publish(PubSubTopics.SPINKIT_MODAL_CLOSE);

        if (nextProps.code !== '200') {
            Alert.alert('', UIConstants.login.login_failed_tips + nextProps.loginFailedMsg, [{text: UIConstants.login.alert_confirm},]);
        }
        
        const {dispatch} = this.props;
        dispatch(clearLoginFailedMsg());
    }

    goToPwdResetPage() {
        this.props.navigatorRoot.resetTo({
            name: Routes.MY_RESETPWD,
            component: MyResetPwdContainer,
            from: Routes.LOGIN,
        });
    }
    
    onSavePwdCheckChangeFunc(checked) {
        this.isSavePwdChecked = checked;
    }

    validateUserName() {
        if (this.state.username === '') {
            return false;
        }
        else {
            return true;
        }
    }

    validatePassword() {
        if (this.state.password === '') {
            return false;
        }
        else {
            return true;
        }
    }

    onLoginFunc() {
        this.usernameInput.blur();
        this.passwordInput.blur();

        if (!this.validateUserName()) {
            toastTip(UIConstants.errors.loginUsernameEmptyError, 'long');
            return;
        }

        if (!this.validatePassword()) {
            toastTip(UIConstants.errors.loginPasswordEmptyError, 'long');
            return;
        }

        PubSub.publish(PubSubTopics.SPINKIT_MODAL_OPEN, UIConstants.login.logining);

        InteractionManager.runAfterInteractions(() => {
            const {dispatch} = this.props;
            dispatch(loginWithUsernamePassword(this.state.username, this.state.password));
        });
    }

    onUsernameInputFocusFunc() {
        if (this.state.username !== '') {
            this.isUsernameInputFocused = true;
        }

        this.setState({});
    }

    onUsernameInputBlurFunc() {
        this.isUsernameInputFocused = false;

        this.setState({});
    }

    clearUsernameInputFunc() {
        this.isUsernameInputFocused = false;

        if (this.isSavePwdChecked) {
            this.isSavePwdChecked = false;
        }
        this.setState({
            username: '',
            password: '',
        });
    }

    onPasswordInputFocusFunc() {
        if (this.state.password !== '') {
            this.isPasswordInputFocused = true;
        }

        this.setState({});
    }

    onPasswordInputBlurFunc() {
        this.isPasswordInputFocused = false;

        this.setState({});
    }

    clearPasswordInputFunc() {
        this.isPasswordInputFocused = false;

        this.setState({
            password: '',
        });
    }

    onChangeUsername(username) {
        if (this.usernameInput.isFocused() && username !== '') {
            this.isUsernameInputFocused = true;
        }
        else {
            this.isUsernameInputFocused = false;
        }

        this.isSavePwdChecked = false;

        this.setState({
            username: username,
            password: '',
        });
    }

    onChangePassword(password) {
        if (this.passwordInput.isFocused() && password !== '') {
            this.isPasswordInputFocused = true;
        }
        else {
            this.isPasswordInputFocused = false;
        }

        this.setState({
            password: password,
        });
    }

    pandaTestButtonPress() {
        // NativeModules.PandaNativeModule.getAppVersionName()
        // .then(
        //     (version) => {
        //         alert(version)
        //     }
        // )
        // .catch(
        //     (err) => {
        //         alert(err)
        //     }
        // );
    }

    getErrorLogs() {
        // LocalStorage.getErrorLogs((errorLogs) => {
        //     alert(JSON.stringify(errorLogs.reverse()));
        // });


        // LocalStorage.clearErrorLogs();
    }

    render() {
        return (
            <View style={styles.container}>
                <View style={styles.logo}>
                    <Image source={Images.Title} style={{width: WINDOW_WIDTH / 2,marginTop:20}} resizeMode={Image.resizeMode.contain} />
                </View>
                <View style={styles.avatarContainer}>
                    <Image source={Images.Logo} style={styles.avatar} resizeMode={Image.resizeMode.contain} />
                </View>
                <View style={styles.inputView}>
                    <Image source={Images.Username} style={styles.inputIcon} resizeMode={Image.resizeMode.contain} />
                    <TextInput 
                        ref={(ref) => {this.usernameInput = ref}}
                        style={styles.inputBox}
                        placeholder={UIConstants.login.username_placeholder}
                        value={this.state.username}
                        underlineColorAndroid={'transparent'}
                        autoCapitalize={'none'}
                        autoCorrect={false}
                        onChangeText={(username) => {this.onChangeUsername(username)}}
                        onFocus={this.onUsernameInputFocus}
                        onBlur={this.onUsernameInputBlur}
                    />
                    {
                        this.isUsernameInputFocused ? 
                        <TouchableOpacity onPress={this.clearUsernameInput}>
                            <Icon style={styles.clearicon} name={'md-close'} size={WINDOW_HEIGHT / 12 / 2} color={Colors.gray} />
                        </TouchableOpacity>
                        : null
                    }
                </View>
                <View style={styles.inputView}>
                    <Image source={Images.Password} style={styles.inputIcon} resizeMode={Image.resizeMode.contain} />
                    <TextInput  
                        ref={(ref) => {this.passwordInput = ref}}
                        style={styles.inputBox}
                        placeholder={UIConstants.login.password_placeholder}
                        value={this.state.password}
                        underlineColorAndroid={'transparent'}
                        autoCapitalize={'none'}
                        autoCorrect={false}
                        secureTextEntry={true}
                        onChangeText={(password) => {this.onChangePassword(password)}}
                        onFocus={this.onPasswordInputFocus}
                        onBlur={this.onPasswordInputBlur}
                    />
                    {
                        this.isPasswordInputFocused ? 
                        <TouchableOpacity onPress={this.clearPasswordInput}>
                            <Icon style={styles.clearicon} name={'md-close'} size={WINDOW_HEIGHT / 12 / 2} color={Colors.gray} />
                        </TouchableOpacity>
                        : null
                    }
                </View>
                <View style={styles.optionView}>
                    <CheckBox
                        label={UIConstants.login.remember_password}
                        labelStyle={{color: Colors.green,}}
                        style={{marginLeft: 24,}}
                        checked={this.isSavePwdChecked}
                        onChange={this.onSavePwdCheckChange}>
                    </CheckBox>
                    <TouchableOpacity style={styles.optionbutton}>
                        <Text style={[styles.optiontext, {textDecorationLine: 'underline'}]}>{UIConstants.login.forget_password}</Text>
                    </TouchableOpacity>
                </View>
                <View style={styles.buttonView}>
                    <Button style={styles.button} text={UIConstants.login.login} textStyle={styles.buttontext} onPress={this.onLogin} />
                </View>
                <View style={[styles.buttonView, {opacity: 0,}]}>
                    <Button style={styles.button} text={'获取本地异常错误日志'} textStyle={styles.buttontext} onPress={() => {this.getErrorLogs()}} />
                </View>
                <View style={[styles.buttonView, {opacity: 0,}]}>
                    <Button style={styles.button} text={'test open link in browser'} textStyle={styles.buttontext} onPress={() => {this.pandaTestButtonPress()}} />
                </View>
                <View style={styles.footer}>
                    <Text style={[styles.footertext, {fontSize: 16}]}>{UIConstants.login.app_name}</Text>
                    <Text style={[styles.footertext, {fontSize: 16}]}>{'（V ' + this.state.appVersion + '）'}</Text>
                </View>

                <ConfirmDialog
                    ref={(ref) => {this.confirmDialog = ref}}
                    title={this.state.title}
                    content={this.state.content}
                    confirmLabel={this.state.confirmLabel}
                    cancelLabel={this.state.cancelLabel}
                    confirmCallback={this.state.confirmFunc}
                    cancelCallback={this.state.cancelFunc}
                    type={this.state.dialogType}
                    iconType={this.state.iconType}
                />
            </View>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        height: WINDOW_HEIGHT,
        flexDirection: 'column',
        backgroundColor: Colors.appBackground,
    },
    logo: {
        flex: 1,
        alignItems: 'center',
        justifyContent: 'center',
    },
    avatarContainer: {
        flex: 4,
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'center',
        borderTopWidth: StyleSheet.hairlineWidth,
        borderTopColor: Colors.gray,
        borderBottomWidth: StyleSheet.hairlineWidth,
        borderBottomColor: Colors.gray,
        marginTop: 20,
    },
    avatar: {
        alignSelf: 'center',
        alignItems: 'center',
        width: WINDOW_WIDTH / 3 * 1.3,
        height: WINDOW_WIDTH / 3 * 1.3,
        borderRadius: WINDOW_WIDTH / 6 * 1.3,
    },
    inputView: {
        flex: 1,
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'center',
        borderBottomWidth: StyleSheet.hairlineWidth,
        borderBottomColor: Colors.gray,
    },
    inputIcon: {
        width: WINDOW_HEIGHT / 12 / 2,
        height: WINDOW_HEIGHT / 12 / 2,
        marginLeft: 24,
    },
    inputBox: {
        flex: 1,
        marginLeft: 8,
        marginRight: 24,
        height: WINDOW_HEIGHT / 12 - 8,
        fontSize: 18,
        alignItems: 'center',
        alignSelf: 'center',
        justifyContent: 'center',
    },
    clearicon: {
        marginLeft: 24,
        marginRight: 24,
    },
    optionView: {
        flex: 1,
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'flex-start',
    },
    checkboxtext: {
        color: Colors.green,
        alignSelf: 'center',
        textAlign: 'left',
        marginLeft: 6,
    },
    optionbutton: {
        flex: 1,
        alignItems: 'center',
        justifyContent: 'center',
    },
    optiontext: {
        alignSelf: 'flex-end',
        marginRight: 24,
        color: Colors.green,
        justifyContent: 'center',
    },
    buttonView: {
        flex: 1,
    },
    button: {
        flex: 1,
        marginLeft: 24,
        marginRight: 24,
        width: WINDOW_WIDTH - 48,
        // height:WINDOW_HEIGHT*0.09
    },
    buttontext: {
        // marginTop: 8,
        // marginBottom: 8,
        fontSize: 20,
    },
    footer: {
        flex: 2,
        justifyContent: 'flex-end',
        alignItems: 'center',
        marginBottom: 12,
    },
    footertext: {
        color: Colors.green,
        marginBottom: 6,
    },
});

export default Login;